package tn.orange.canreminder.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import tn.orange.canreminder.conf.Config;
import tn.orange.canreminder.model.Country;
import tn.orange.canreminder.model.JSONCountries;
import tn.orange.canreminder.model.JSONOpinions;
import tn.orange.canreminder.model.JSONPlacesCategory;
import tn.orange.canreminder.model.Opinion;
import tn.orange.canreminder.parse.GenericJsonParser;

public class OpinionServiceImp implements OpinionService {

	GenericJsonParser parser = new GenericJsonParser();

	@Override
	public void submitOpinion(Opinion opinion) throws Exception {

		GenericJsonParser parser = new GenericJsonParser();
		// TODO Auto-generated method stub
		HttpClient httpclient = new DefaultHttpClient();

		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("username", opinion
				.getUsername()));
		nameValuePairs.add(new BasicNameValuePair("place_id", ""
				+ opinion.getPlace_id()));
		nameValuePairs.add(new BasicNameValuePair("article", opinion
				.getArticle()));

		HttpPost httppost = new HttpPost(Config.submitopinion);

		httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		httpclient.execute(httppost);

	}

	private StringBuilder inputStreamToString(InputStream is)
			throws IOException {
		String line = "";
		StringBuilder total = new StringBuilder();

		// Wrap a BufferedReader around the InputStream
		BufferedReader rd = new BufferedReader(new InputStreamReader(is));

		// Read response until the end
		while ((line = rd.readLine()) != null) {
			total.append(line);
		}

		// Return full string
		return total;
	}

	@Override
	public List<Opinion> getAllOpinions(int placeId) throws Exception {
		// TODO Auto-generated method stub

		parser.setOutput(JSONOpinions.class);
		parser.setUrl(Config.opinions + "" + placeId + "/all.json");
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		parser.setNameValuePairs(nameValuePairs);
		JSONOpinions object = (JSONOpinions) parser.parse();
		List<Opinion> opinions = object.getCountries();
		return opinions;

	}
}
